﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SoftHotel.Models;
using PagedList;
using System.Data;
using System.Data.Entity;

namespace SoftHotel.Controllers
{
    public class ClientesController : Controller
    {
        //
        // GET: /Cliente/
        private ClienteDAO db = new ClienteDAO();
        private ParametroDAO dbPar = new ParametroDAO();

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(Cliente cliente, string button)
        {
            if (button == "Buscar")
            {
                return RedirectToAction("Buscar", cliente); //Model de Buscar es IEnumerable (*)
            }
            else
                return RedirectToAction("Create");
        }

        public ActionResult Buscar(string sortOrder, string currentFilter, string searchString, int? page)
        {
            ViewBag.SortActual = sortOrder;
            ViewBag.NombreSort = String.IsNullOrEmpty(sortOrder) ? "Name Desc" : "";

            if (Request.HttpMethod == "GET")
            {
                searchString = currentFilter;
            }
            else
            {
                page = 1;
            }
            ViewBag.CurrentFilter = searchString;
            

            var clientesAux = db.clientes.Include(a => a.objeTipoDoc).Include(a => a.objEstado).Include(a => a.objTipoCliente);//from c in db.clientes select c;


            if (!String.IsNullOrEmpty(searchString))
            {
                clientesAux = clientesAux.Where(s => s.apellidoPaterno.ToUpper().Contains(searchString.ToUpper())
                                       || s.nombres.ToUpper().Contains(searchString.ToUpper())
                                       || s.apellidoMaterno.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrder)
            {
                case "Name Desc":
                    

                    break;
                default:
                    clientesAux = clientesAux.OrderByDescending(s => s.apellidoPaterno.ToLower());
                    break;
            }

            int tamanhoPagina = 5;
            int NumPagina = (page ?? 1);

            return View(clientesAux.ToPagedList(NumPagina, tamanhoPagina));
        }

        //
        // GET: /Cliente/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Cliente/Create

        public ActionResult Create()
        {
            ViewBag.tipoDoc = new SelectList(dbPar.parametros.Where(j => j.tipo == "TIPO_DOCUMENTO_ID"), "idParametro", "valor");
            ViewBag.tipoCliente = new SelectList(dbPar.parametros.Where(u => u.tipo == "TIPO_CLIENTE"), "idParametro", "valor");

            return View();
        } 

        //
        // POST: /Cliente/Create

        [HttpPost]
        public ActionResult Create(Cliente cliente, string button)
        {
            if (ModelState.IsValid)
            {

            }
            if (button == "Cancelar")
                return RedirectToAction("Index");

            else//if (button == "Create")
            {
                int a;
                var aux2 = from d in db.clientes where d.numDoc == cliente.numDoc && d.tipoDoc == cliente.tipoDoc select d;

                if (aux2.ToList().Count() > 0)
                {
                    //ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
                    return RedirectToAction("Create");
                }

                var aux = from c in dbPar.parametros where c.tipo == "ESTADO_CLIENTE" && c.valor == "Activo" select c;
                List<Parametro> lista = new List<Parametro>();

                foreach (Parametro par in aux)
                {
                    lista.Add(par);
                }

                cliente.estado = lista[0].idParametro;

                //aux.ToList();
                //var aux = dbPar.parametros.Where(a => a.tipo == "ESTADO_CLIENTE").Where(a => a.valor == "Activo").First();
                //cliente.estado = aux;

                try
                {
                    db.RegistrarCliente(cliente);
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
            
            
        }
        
        //
        // GET: /Cliente/Edit/5

     /*   public ActionResult Edit(Cliente cliente)
        {

            if (cliente.nombres != null)
            {
                ViewBag.tipoDoc = new SelectList(dbPar.parametros.Where(j => j.tipo == "TIPO_DOCUMENTO_ID"), "idParametro", "valor");
                return View(cliente);
            }
            else
                return RedirectToAction("editJuridico", cliente);
        }*/

        public ActionResult Edit(int idCliente)
        {
            Cliente cliente = db.clientes.Find(idCliente);
            if (cliente.nombres != null)
            {
                ViewBag.tipoDoc = new SelectList(dbPar.parametros.Where(j => j.tipo == "TIPO_DOCUMENTO_ID"), "idParametro", "valor");
                return View(cliente);
            }
            else
                return RedirectToAction("editJuridico", cliente);
        }


        //
        // POST: /Cliente/Edit/5

        [HttpPost]
        public ActionResult Edit(Cliente cliente, object dummy)
        {
            try
            {
                    db.Entry(cliente).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                
            }
            catch
            {
                return View();
            }
        }


        public ActionResult EditJuridico(Cliente cliente)
        {

            ViewBag.tipoDoc = new SelectList(dbPar.parametros.Where(j => j.tipo == "TIPO_DOCUMENTO_ID"), "idParametro", "valor");
            return View(cliente);

        }

        //
        // POST: /Clientes/Edit/5

        [HttpPost]
        public ActionResult EditJuridico(Cliente cliente, object dummy)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(cliente).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                return View();
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Cliente/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Cliente/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
